package com.carol.lmsbe.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.carol.lmsbe.dto.*;
import com.carol.lmsbe.entity.EquipmentApplication;
import com.carol.lmsbe.entity.Laboratory;
import com.carol.lmsbe.entity.User;
import com.carol.lmsbe.mapper.EquipmentApplicationMapper;
import com.carol.lmsbe.mapper.LaboratoryMapper;
import com.carol.lmsbe.mapper.UserMapper;
import com.carol.lmsbe.service.EquipmentApplicationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 设备申请服务实现
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class EquipmentApplicationServiceImpl implements EquipmentApplicationService {

    private final EquipmentApplicationMapper equipmentApplicationMapper;
    private final UserMapper userMapper;
    private final LaboratoryMapper laboratoryMapper;

    @Override
    public Page<EquipmentApplicationDTO> listApplications(EquipmentApplicationQueryRequest request) {
        Page<EquipmentApplication> page = new Page<>(request.getPageNum(), request.getPageSize());
        
        LambdaQueryWrapper<EquipmentApplication> queryWrapper = new LambdaQueryWrapper<>();
        
        if (request.getApplicantId() != null) {
            queryWrapper.eq(EquipmentApplication::getApplicantId, request.getApplicantId());
        }
        if (StringUtils.hasText(request.getStatus())) {
            queryWrapper.eq(EquipmentApplication::getStatus, request.getStatus());
        }
        if (request.getApplicationDateStart() != null) {
            queryWrapper.ge(EquipmentApplication::getCreateTime, request.getApplicationDateStart().atStartOfDay());
        }
        if (request.getApplicationDateEnd() != null) {
            queryWrapper.le(EquipmentApplication::getCreateTime, request.getApplicationDateEnd().atTime(23, 59, 59));
        }
        if (StringUtils.hasText(request.getEquipmentName())) {
            queryWrapper.like(EquipmentApplication::getName, request.getEquipmentName());
        }
        if (StringUtils.hasText(request.getEquipmentCategory())) {
            queryWrapper.eq(EquipmentApplication::getCategory, request.getEquipmentCategory());
        }
        
        queryWrapper.orderByDesc(EquipmentApplication::getCreateTime);
        
        Page<EquipmentApplication> applicationPage = equipmentApplicationMapper.selectPage(page, queryWrapper);
        
        // 转换为DTO
        Page<EquipmentApplicationDTO> result = new Page<>();
        BeanUtils.copyProperties(applicationPage, result, "records");
        
        List<EquipmentApplicationDTO> records = applicationPage.getRecords().stream().map(application -> {
            EquipmentApplicationDTO dto = new EquipmentApplicationDTO();
            BeanUtils.copyProperties(application, dto);
            
            // 手动映射字段名不匹配的属性
            dto.setEquipmentName(application.getName());
            dto.setPurpose(application.getReason());
            dto.setEstimatedPrice(application.getUnitPrice() != null ? application.getUnitPrice().toString() : null);
            
            // 设置申请人姓名
            if (application.getApplicantId() != null) {
                User applicant = userMapper.selectById(application.getApplicantId());
                if (applicant != null) {
                    dto.setApplicantName(applicant.getRealName());
                }
            }
            
            // 设置审批人姓名
            if (application.getApproverId() != null) {
                User approver = userMapper.selectById(application.getApproverId());
                if (approver != null) {
                    dto.setApproverName(approver.getRealName());
                }
            }
            
            // 设置实验室名称
            if (application.getLaboratoryId() != null) {
                Laboratory laboratory = laboratoryMapper.selectById(application.getLaboratoryId());
                if (laboratory != null) {
                    dto.setLaboratoryName(laboratory.getName());
                }
            }
            
            return dto;
        }).collect(Collectors.toList());
        
        result.setRecords(records);
        return result;
    }

    @Override
    public EquipmentApplicationDTO getApplicationById(Long id) {
        EquipmentApplication application = equipmentApplicationMapper.selectById(id);
        if (application == null) {
            throw new RuntimeException("申请记录不存在");
        }
        
        EquipmentApplicationDTO dto = new EquipmentApplicationDTO();
        BeanUtils.copyProperties(application, dto);
        
        // 手动映射字段名不匹配的属性
        dto.setEquipmentName(application.getName());
        dto.setPurpose(application.getReason());
        dto.setEstimatedPrice(application.getUnitPrice() != null ? application.getUnitPrice().toString() : null);
        
        // 设置申请人姓名
        if (application.getApplicantId() != null) {
            User applicant = userMapper.selectById(application.getApplicantId());
            if (applicant != null) {
                dto.setApplicantName(applicant.getRealName());
            }
        }
        
        // 设置审批人姓名
        if (application.getApproverId() != null) {
            User approver = userMapper.selectById(application.getApproverId());
            if (approver != null) {
                dto.setApproverName(approver.getRealName());
            }
        }
        
        // 设置实验室名称
        if (application.getLaboratoryId() != null) {
            Laboratory laboratory = laboratoryMapper.selectById(application.getLaboratoryId());
            if (laboratory != null) {
                dto.setLaboratoryName(laboratory.getName());
            }
        }
        
        return dto;
    }

    @Override
    @Transactional
    public EquipmentApplicationDTO createApplication(EquipmentApplicationRequest request) {
        // 获取当前用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long currentUserId = getCurrentUserId(authentication);
        
        EquipmentApplication application = new EquipmentApplication();
        
        // 手动映射字段，因为DTO和Entity字段名不完全匹配
        application.setName(request.getEquipmentName());
        application.setCategory(request.getEquipmentCategory());
        application.setQuantity(request.getQuantity());
        application.setUnitPrice(request.getUnitPrice());
        application.setReason(request.getReason());
        application.setApplicantId(currentUserId);
        application.setStatus("PENDING"); // 默认状态为待审批
        
        // 设置实验室ID - 从当前用户获取
        User currentUser = userMapper.selectById(currentUserId);
        if (currentUser != null && currentUser.getLaboratoryId() != null) {
            application.setLaboratoryId(currentUser.getLaboratoryId());
        }
        
        equipmentApplicationMapper.insert(application);
        
        return getApplicationById(application.getId());
    }

    @Override
    @Transactional
    public EquipmentApplicationDTO updateApplication(EquipmentApplicationUpdateRequest request) {
        EquipmentApplication application = equipmentApplicationMapper.selectById(request.getId());
        if (application == null) {
            throw new RuntimeException("申请记录不存在");
        }
        
        // 只有待审批状态的申请才能修改
        if (!"PENDING".equals(application.getStatus())) {
            throw new RuntimeException("只有待审批状态的申请才能修改");
        }
        
        BeanUtils.copyProperties(request, application);
        equipmentApplicationMapper.updateById(application);
        
        return getApplicationById(application.getId());
    }

    @Override
    @Transactional
    public void deleteApplication(Long id) {
        EquipmentApplication application = equipmentApplicationMapper.selectById(id);
        if (application == null) {
            throw new RuntimeException("申请记录不存在");
        }
        
        // 只有待审批状态的申请才能删除
        if (!"PENDING".equals(application.getStatus())) {
            throw new RuntimeException("只有待审批状态的申请才能删除");
        }
        
        equipmentApplicationMapper.deleteById(id);
    }

    @Override
    @Transactional
    public EquipmentApplicationDTO approveApplication(EquipmentApplicationApprovalRequest request) {
        EquipmentApplication application = equipmentApplicationMapper.selectById(request.getApplicationId());
        if (application == null) {
            throw new RuntimeException("申请记录不存在");
        }
        
        // 只有待审批状态的申请才能审批
        if (!"PENDING".equals(application.getStatus())) {
            throw new RuntimeException("只有待审批状态的申请才能审批");
        }
        
        // 获取当前用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long currentUserId = getCurrentUserId(authentication);
        
        application.setStatus(request.getStatus());
        application.setApproverId(currentUserId);
        application.setApprovalTime(request.getApprovalDate().atStartOfDay());
        application.setApprovalComment(request.getApprovalComment());
        
        equipmentApplicationMapper.updateById(application);
        
        return getApplicationById(application.getId());
    }

    @Override
    public Page<EquipmentApplicationDTO> getMyApplications(EquipmentApplicationQueryRequest request) {
        // 获取当前用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long currentUserId = getCurrentUserId(authentication);
        
        request.setApplicantId(currentUserId);
        return listApplications(request);
    }

    @Override
    public Page<EquipmentApplicationDTO> getPendingApplications(EquipmentApplicationQueryRequest request) {
        request.setStatus("PENDING");
        return listApplications(request);
    }

    @Override
    @Transactional
    public void batchDeleteApplications(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return;
        }
        
        equipmentApplicationMapper.deleteBatchIds(ids);
    }

    @Override
    public byte[] exportApplicationData(EquipmentApplicationQueryRequest request) {
        // 这里可以实现Excel导出逻辑
        // 暂时返回空数组
        return new byte[0];
    }

    /**
     * 获取当前用户ID
     */
    private Long getCurrentUserId(Authentication authentication) {
        if (authentication == null || authentication.getPrincipal() == null) {
            throw new RuntimeException("用户未登录");
        }
        
        Object principal = authentication.getPrincipal();
        if (principal instanceof com.carol.lmsbe.security.JwtAuthenticationFilter.UserPrincipal) {
            return ((com.carol.lmsbe.security.JwtAuthenticationFilter.UserPrincipal) principal).getUserId();
        } else if (principal instanceof String) {
            // 如果principal是用户名，则通过用户名查找用户ID
            User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                    .eq(User::getUsername, principal));
            if (user != null) {
                return user.getId();
            }
        }
        
        throw new RuntimeException("无法获取当前用户信息");
    }
}
